package com.study.it.hystrix.command;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.study.it.dubbo.face.RecordDubbo;
import com.study.it.entity.Account;
import com.study.it.entity.Record;

import java.lang.reflect.Method;

//重载HystrixCommand 的getFallback方法实现逻辑
public class DubboCommand<T> extends HystrixCommand<T> {
    private Object service;//对象
    private Object[] args;//参数(个数不确定)
    private Method method;//方法
    private T errObj;//出错时候，返回的对象

    public DubboCommand(Object _service,Method _method,Object[] _args,T _errObj ) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("myGroup"))
                /* 配置依赖超时时间,500毫秒*/
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationThreadTimeoutInMilliseconds(500)));
        this.service=_service;
        this.method=_method;
        this.args=_args;
        this.errObj=_errObj;
    }

    public DubboCommand(Object _service,String _methodname,Object[] _args,T _errObj ) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("myGroup"))
                /* 配置依赖超时时间,500毫秒*/
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter().withExecutionIsolationThreadTimeoutInMilliseconds(500)));
       try {
           //动态获取参数类型
           Class[] classes=new Class[_args==null?0:_args.length];

           for(int i=0;_args!=null&&i<_args.length;i++)
             classes[i]=_args[i].getClass();

           this.service = _service;
           this.method = this.service.getClass().getMethod(_methodname,classes);
           this.args = _args;
           this.errObj = _errObj;
       }catch(Exception ex)
       {
           ex.printStackTrace();
           throw new RuntimeException(ex.getMessage(),ex);
       }
    }


    @Override
    protected T getFallback() {//如果发生错误，就返回一个特别的对象
        System.out.println("超时了调用getFallback");
        return errObj;
    }
    @Override
    protected T run() throws Exception {
        System.out.println("Hystrix调用getFallback");
        return (T)method.invoke(service,args);//反射的方式
        //return  service.method(params);
    }

}
